<template>
  <div class="page">
    <!-- 导航栏 -->
    <div class="navBar">
      <img src="../../assets/img/fhb.png" alt="" @click="goback()">
      <div>{{titleTest}}</div>
    </div>
    <!-- 页面内容 -->
    <div class="content">
      <van-form class="contentView" @failed="onFailed" ref="forms" @submit="customers">
        <van-cell-group inset>
          <!-- 姓名-->
          <van-field label="姓名" placeholder="如填写，请填写真实准确姓名"  v-model="customName" name="姓名" :maxlength="32" input-align="right" autocomplete="off"
            :rules="zhrules" />
          <!-- 证件类型 -->
          <!-- <van-field label="证件类型"  v-model="credTypeBackups" name="证件类型" readonly input-align="right" /> -->
          <!-- :disabled="customName?false:true" -->
          <van-field
           v-model="credTypeBackups"
           is-link
           readonly
           name="picker"
           label="证件类型"
           autocomplete="off"
           placeholder="点击选择证件类型"
           @click="carShowClick"
          />
          <van-popup v-model:show="carshowPicker" position="bottom">
            <van-picker
              :columns="carcolumns"
              @confirm="caronConfirm"
              
              @cancel="cancel"
            />
          </van-popup>
          <!-- :disabled="customName?false:true" -->
          <span v-if="credTypeBackups=='' && credNum!=''" class="crn">您已填写证件号码，请选择证件类型</span>
          <!-- 通过 validator 进行身份证格式校验 -->
          <van-field label="身份证号码" v-model="credNum"  maxlength=18 name="validator" placeholder="请输入身份证号码" autocomplete="off"
            input-align="right" :rules="[{ validator, message: '身份证号码格式错误！' }]" />

          <!-- 性别 -->
          <van-field name="sex" v-if="false" label="性别" :disabled="customName?false:true"   readonly input-align="right">
            <template #input>
              <van-radio-group  v-model="sex" direction="horizontal">
                <van-radio name="0">男</van-radio>
                <van-radio name="1">女</van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <!-- 出生日期 -->
          <!-- is-link 右边箭头 -->
          <van-field v-model="birthday" v-if="false" :disabled="customName?false:true" readonly name="datePicker" label="出生日期" input-align="right" />

          <!-- 报告类型 -->
          <van-field name="reportType" label="报告类型*" input-align="right">
            <template #input>
              <van-radio-group v-model="reportType" direction="horizontal">
                <van-radio name="1">简版
                  <template #icon="props">
                    <img style="width: 13px; height: 13px; margin-top: 3px;" class="img-icon" :src="props.checked ? activeIcon : inactiveIcon" />
                  </template>
                </van-radio>
                <van-radio name="2">详版
                  <template #icon="props">
                    <img style="width: 13px; height: 13px; margin-top: 3px;" class="img-icon" :src="props.checked ? activeIcon : inactiveIcon" />
                  </template>
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>

          <van-field v-model="reportParam" is-link readonly name="picker" label="演示期间 *" placeholder="终身" input-align="right"
            @click="reportParamShowPicker = true" />
          <van-popup v-model:show="reportParamShowPicker" position="bottom">
            <van-picker :columns="columns" @confirm="reportParamOnConfirm" @cancel="reportParamShowPicker = false" />
          </van-popup>
          <van-field label="任务备注" v-model="remark"  rows="3" autosize  type="textarea" :maxlength="80" input-align="right" placeholder="您可以在此处输入备注信息"/>
          <!-- 证件类型 -->
          <div class='seat'></div>
        </van-cell-group>

        <div style="margin: 20px; margin-top:28px;">
          <van-button class="primaryButton" round block type="primary" native-type="customers">
            发起邀请
          </van-button>
        </div>
        <!-- <div style="margin: 20px; margin-top:28px;" @click="customers()">
          <van-button class="primaryButton" block> 发起邀请</van-button>
        </div> -->
      </van-form>

    </div>
  </div>
</template>

<script lang="ts" setup name="addCustomersz">
import { useRouter, useRoute } from "vue-router"
import { Toast } from '/@/utils/Message';
import { onMounted } from "vue"
import { reactive, ref } from 'vue'
import { createInspectionTask, inviteAgain } from "/@/api/auth/wart"
import customNavBar from "/src/components/NavBar/customNavBar.vue"
import { sm2 } from 'sm-crypto';
import activeIcon from "../../assets/img/features/activeIcon.png"
import inactiveIcon from "../../assets/img/features/inactiveIcon.png"
//公钥串---加密使用
const publicKey = ref<string>("044291b381a039a8d7d02d7272d2d7c78a30d33e3eeaa0b509bf77d2376582ab2d573730e6bfe9a53bad53f53ac1a85d9c11050931f04bc8b3afc04144d5a6f9be")
//私钥串---解密使用
const privateKey = ref<string>("5aa03412c3051e1d4cf9d19cfbeeec70c28f388c9f82747cc912096c9cd44bea")
const router = useRouter()
const route = useRoute()
let forms = ref()
// const zhrules = [{ required: true, message: '请输入姓名' }, { pattern: /^.{2,}$/, message: '姓名格式错误', trigger: 'onBlur' }]
const leftTetx = ref<string>("")
const titleTest = ref<string>("添加客户-再次邀请")
const carshowPicker = ref(false);
//证件类型
const credType = ref<string>("")
const credType1 = ref<string>("")
const credTypeBackups = ref<string>("")
const carcolumns = [
  { text: '身份证', value: '111' },
];

const caronConfirm = ({ selectedOptions }) => {
  credTypeBackups.value = selectedOptions[0]?.text;
  credType.value = selectedOptions[0]?.value
  carshowPicker.value = false;
};
const cancel = () => {
  credTypeBackups.value = ''
  credType.value = ''
  carshowPicker.value = false
}
//用户姓名
const customName = ref<string>("")
const customNameBackups = ref<string>("")
//身份证号码
const credNum = ref<string>("")
const credNumShow = ref<boolean>(true)
const credNumBackups = ref<string>("")
//性别
let sex = ref<string>('');
//报告类型
const reportType = ref<string>("")
//出生日期
const birthday = ref<string>('');
//备注
const remark = ref<string>('')
const showPicker = ref<boolean>(false);
const onConfirm = ({ selectedValues }:any):void => {
  birthday.value = selectedValues.join('-');
  showPicker.value = false;
}
onMounted(()=>{
  inviteAgain(route?.query).then((res: any) => {
      // console.log(res)
      if(res.code == 200) {
        columns.map(v => {
          if(v.text == res.customVO.reportParam) {
            reportParam.value = v.value
          }
        })
        if(res.customVO.credType == '111') {
          credTypeBackups.value = '身份证'
        }
        credType.value = res.customVO.credType
        credType1.value = res.customVO.credType
        customNameBackups.value = res.customVO.customName 
        customName.value = res.customVO.customName
        credNumBackups.value =  res.customVO.credNum
        credNum.value = res.customVO.credNum
        sex.value = res.customVO.sex
        remark.value = res.customVO.remark
        reportType.value = res.customVO.reportType
        if(reportType.value == '3'){
          reportType.value = '2'
        }
        birthday.value = res.customVO.birthday
      }
  })
})
//和业务需求核对日期
//1.开始日期
const minDate = ref(new Date(1900, 0, 1))
//2.当前日期
const maxDate = ref(new Date())
const formatter = (type, option) => {
  if (type === 'year') {
    option.text += '年';
  }
  if (type === 'month') {
    option.text += '月';
  }
  if (type === 'day') {
    option.text += '日';
  }
  return option;
};

//参数
const reportParamName = ref<string>("3")
const reportParam = ref<string>("终身")
const reportParamShowPicker = ref(false);
const reportParamOnConfirm = ({ selectedOptions }) => {
  // console.log(selectedOptions)
  reportParam.value = selectedOptions[0]?.text;
  reportParamName.value = selectedOptions[0]?.value;
  reportParamShowPicker.value = false;
};

const columns = [
  { text: '10年', value: '0' },
  { text: '20年', value: '1' },
  { text: '30年', value: '2' },
  { text: '终身', value: '3' },
];

const goback = ():void => {
    // Toast('返回上一页面')
    router.go(-1)
}
const validatorName =(v:any)=>{
  if(v){
    const testName = /^.{2,}$/
    return testName.test(v)
  }else{
    // console.log("清空了姓名")
    // //清空姓名后，需要清除证件类型、证件号码’性别、出生日期
    // credType.value = ''
    // credNum.value = ''
    // sex.value = ''
    // birthday.value = ''
  }
}
// 姓名校验规则
const zhrules = [
  { required: false, message: '请输入姓名' }, 
  { validator:validatorName, message: '姓名格式错误' } 
]
// 证件类型点击事件
const carShowClick = ()=>{
  carshowPicker.value = true
  return
  if(!!customName.value){
    carshowPicker.value = true
  }else{
    Toast('请先输入姓名')
  }
}

//身份证校验规则
const validator = (v) => {
  if(v == credNumBackups.value){
    return true
  } else {
    if(v){
      const card15 = /^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$/
      const card18 = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      // 出生日期
      const regexp = /^(\d{6})(\d{4})(\d{2})(\d{2})\d{3}(\w)$/;
      if (card15.test(v) || card18.test(v)) {
        /** idCard  '1'= 男  '2'= 女*/
        // console.log("身份证输入正确！")
        birthday.value = getBirthday(v)
        // console.log(parseInt(v.slice(-2, -1), 10) % 2)
        if (parseInt(v.slice(-2, -1), 10) % 2 == 1) {
          sex.value = '0'
          // console.log("身份证 男")
        } else {
          sex.value  = '1'
          // console.log("身份证 女")
        }
      } else {
        sex.value  = '2'
      }
      credNumShow.value = card15.test(v) || card18.test(v)
      return card15.test(v) || card18.test(v)
    } else {
      credNumShow.value = true
    }
  }
}
const getBirthday = (idCard) => {
    let birthday = '';
    if (idCard.length === 15) {
      birthday = '19' + idCard.substring(6, 12);
    } else if (idCard.length === 18) {
      birthday = idCard.substring(6, 14);
    }
    return birthday.replace(/(.{4})(.{2})(.{2})/, '$1-$2-$3')
  }

const onFailed = (errorInfo):void => {
  console.log('failed', errorInfo);
};
// 加密方法
const JIAMIPublicData=(data)=> {
    const cipherMode = 1;
    const result = sm2.doEncrypt(data, publicKey.value,cipherMode);
    return `04${result}`;
}
// 解密方法
const JIMIPublicData=(data)=> {
    const cipherMode = 1;
    //data为加密的数据
    const result = sm2.doDecrypt(data, privateKey.value,cipherMode).split('04')[1]
    return result;
}
// 邀请客户
const customers = ():void => {
  //if(customName.value){
  //     if(!credType.value){
  //       Toast('请填写证件类型')
  //       return
  //     }
  //     if(!credNum.value){
  //       Toast('请填写证件号码')
  //       return
  //     }
  //}
    if(!customName.value){
      if(credType.value){
        Toast('请输入姓名')
        return
      }
      if(credNum.value){
        Toast('请输入姓名')
        return
      }
    }
  if(!credNumShow.value){
    Toast('身份证格式错误')
    return
  }
  // return
  if(credTypeBackups.value=='' && credNum.value!='') {
    Toast('确保被检视对象用户证件类型和被检视对象用户证件号码全部非空或者全部为空')
    return
  }
  let data = {
    // credType: credNum.value ? "*":'',
    credType: credType.value == credType1.value ? "*": credType.value,
    reportParam: reportParamName.value,
    customName: customName.value == customNameBackups.value ? '*': customName.value ? JIAMIPublicData(customName.value): '',
    // customName: customName.value == customNameBackups.value ? '*': JIAMIPublicData(customName.value),
    // credNum: credNum.value == credNumBackups.value? '*' : JIAMIPublicData(credNum.value),
    credNum: credNum.value == credNumBackups.value? '*' : credNum.value == '' ? '' : JIAMIPublicData(credNum.value),
    sex: sex.value,
    reportType: reportType.value,
    birthday:birthday.value,
    remark: remark.value,
    ...route?.query
  }
  // console.log(customName.value)
  // console.log(data)
  // return
  createInspectionTask(data).then((res: any) => {
      Toast(res.msg)
      // return
      if(res.code == 200) {
        sessionStorage.setItem('taskCode',res.taskCode)
        setTimeout(() => {
          router.push({ path: '/inviteCode', query: { expirationTime: res.expirationTime, longUrl: res.longUrl, shortUrl: res.shortUrl ,isShow:1} })
        }, 1700);
      }
  })
  
}
</script>

<!-- less嵌套设置 -->
<style>
.van-field__control:read-only {
 text-align: right;
}
</style>
<style lang="less" scoped>
.crn{
  font-size: 12px;
  color: rgb(255, 0, 0);
}
.page {
  height: 100vh;
  width: 100vw;
  background: linear-gradient(360deg, #F5F7FA 30%, #2890F9 90%, #298BF0 100%);
  box-shadow: 0px 4 8px 0px rgba(0,101,204,0.15), 0px 1 2px 0px #90CEF6;
  .navBar {
    width: 100%;
    height: 44px;
    display: flex;
    padding: 0 12px;
    color: #FFFFFF;
    padding-top: 17px;
    align-items: center;
    img {
      width: 17px;
      height: 17px;
    }
    div {
      width: 90%;
      text-align: center;
    }
  }

  .content {
      width:95%;
    margin: 0 auto;
    margin-top: 18px;
    :deep(.van-cell-group--inset) {
      padding: 0 10px;
    }
    :deep(.van-cell) {
      margin-top: 27px;
      border-radius: 4px;
      background: #F6F9FD;
    }
    .seat {
      width: 100%;
      height: 30px;
    }

    .primaryButton {
      margin-top: 28px;
      // width: 100%;
      width: 80%;
      height: 58px;
      margin: 0 auto;
      background: url("/src/assets/img/loginIcon/loginBut.png");
      background-size: 100% 100%;
      border: none;
      color: white;
      font-size: 16px;
      margin-bottom: 5px;
    }
  }
}
</style>

<!-- 
  姓名	        输入	  文本框	   是		   只可输入为2-32位字符
  身份证号	     输入	   文本框	    是		
  性别	        仅展示	 文本			        根据输入的身份证号，自动识别出性别进行展示
  出生日期	     仅展示	  文本			       根据输入的身份证号，自动识别出出生日期进行展示，格式为YYYY-MM-DD
  报告类型	     选择	   单选按钮	  是		
  演示期间	     选择	   下拉框	    是		 演示期间有终身、30年、20年、10年，默认勾选终身。
  生成邀请链接		按钮			
-->

<!-- 250103  根据需求进行修改
  姓名       输入  文本框   否     如果输入为2-32位字符
  证件类型   选择  弹出框   否      必须输入姓名后才可进行选择  并且如果姓名清空后，清空证件类型、身份证、性别、出生日期  全部置空
  身份证号码 输入框 弹出框  否      必须输入姓名后才可进行选择  并且如果姓名清空后，清空证件类型、身份证、性别、出生日期  全部置空
  性别       选择  单选     否      必须输入姓名后才可进行选择  并且如果姓名清空后，清空证件类型、身份证、性别、出生日期  全部置空
  出生日期   输入  文本框   否      必须输入姓名后才可进行选择  并且如果姓名清空后，清空证件类型、身份证、性别、出生日期  全部置空
  
  报告类型   单选   单选框   是
  演示期间   选择   弹出框   是
  任务备注 输入   文本框  否
-->